package com.houxiurong.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Map;

/**
 * Created by houxiurong on 2017/6/13.
 */
public class HttpHelper {

    /**
     * httpPost请求调用信息平台接口
     *
     * @param url
     * @param body
     * @return
     * @throws IOException
     */
    public static String httpsPost(String url, String body) throws IOException {
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        StringEntity postingString = new StringEntity(body, "UTF-8");
        post.setEntity(postingString);
        post.setHeader("Content-type", "application/json");
        HttpResponse response = httpClient.execute(post);
        String content = EntityUtils.toString(response.getEntity());
        return content;
    }

    /**
     * httpPost请求调用信息平台接口
     *
     * @param url
     * @return
     * @throws IOException
     */
    public static String httpsGet(String url) throws IOException {
        HttpClient httpClient = HttpClients.createDefault();
        HttpGet get = new HttpGet(url);
        HttpResponse response = httpClient.execute(get);
        HttpEntity entity = response.getEntity();
        return EntityUtils.toString(entity);
    }

    /**
     * httpPost请求调用信息平台接口
     *
     * @param url
     * @return
     * @throws IOException
     */
    public static Map<String,Object> doGet(String url) throws IOException{
        HttpClient httpClient = HttpClients.createDefault();
        HttpGet get = new HttpGet(url);
        HttpResponse response = httpClient.execute(get);
        HttpEntity entity = response.getEntity();
        String content = EntityUtils.toString(entity);
        Map<String, Object> map = JSONUtils.parse(content.toString(), Map.class);
        return map;
    }

}
